#include <iostream>
#include <vector>
#include <semaphore.h>
#include <pthread.h>
 
namespace ns_ring_queue
{
    int g_cap_default = 10;

    template <class T>
    class RingQueue
    {
    public:
        RingQueue(int cap = g_cap_default)
          :  _rq(cap)
        {
            _cap = cap;
            sem_init(&_blank_sem,0, cap);
            sem_init(&_data_sem, 0, 0);
            _c_step = _p_step = 0;
            pthread_mutex_init(&_c_mtx, nullptr);
            pthread_mutex_init(&_p_mtx, nullptr);
        }

        ~RingQueue()
        {
            sem_destroy(&_blank_sem);
            sem_destroy(&_data_sem);
            pthread_mutex_destroy(&_c_mtx);
            pthread_mutex_destroy(&_p_mtx);
        }

    public:
        void push(const T &in)
        { 
            sem_wait(&_blank_sem);//P操作
            pthread_mutex_lock(&_p_mtx);//加锁,在申请信号量之后，可以提高效率
            _rq[_p_step] = in;
            _p_step++;
            _p_step %= _cap;
            pthread_mutex_unlock(&_p_mtx);//解锁
            sem_post(&_data_sem);//V操作

        }

        void pop(T *out)
        {
            sem_wait(&_data_sem);//P操作
            pthread_mutex_lock(&_c_mtx);
            *out = _rq[_c_step];
            _c_step++;
            _c_step %= _cap;
            pthread_mutex_unlock(&_c_mtx);
            sem_post(&_blank_sem);//V操作
        }

    private:
        std::vector<T> _rq;
        int _cap;
        //生产者关系空位置资源
        sem_t _blank_sem;
        //消费者只关心数据资源
        sem_t _data_sem;
        int _c_step;
        int _p_step;
        pthread_mutex_t _c_mtx;//消费者之间互斥
        pthread_mutex_t _p_mtx;//生产者之间互斥
    };
}
